/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.client.utils;

import java.util.Arrays;
import java.util.Comparator;

/**
 *
 * @author czarek
 */
public class DomainComparator implements Comparator<String> {

    private static final Comparator<String> INSTANCE = new DomainComparator();

    public static Comparator<String> getInstance() {
        return INSTANCE;
    }
    
    
    
    private  DomainComparator() {
    }
    
    

    @Override
    public int compare(String o1, String o2) {
        String[] o1a = o1.split("\\.");
        String[] o2a = o2.split("\\.");
        final int cmpLen = Math.min(o1a.length,o2a.length);
        final int maxLen = Math.max(o1a.length,o2a.length);
        o1a = Arrays.copyOfRange(o1a,o1a.length-cmpLen,o1a.length);
        o2a = Arrays.copyOfRange(o2a,o2a.length-cmpLen,o2a.length);
        assert(o1a.length==o2a.length && o2a.length==cmpLen);
        int i;   
        int dif=0;
        for(i=cmpLen-1; i>=0; --i){
            if((dif=o1a[i].compareToIgnoreCase(o2a[i]))!=0||i==0){
                break;
            }
        }
        
        final int difLen = o2a.length - o1a.length;
        final int ifak = (dif==0)?0:((dif>0)?4:-4);
        if(i==0){
            return (int)(Math.signum(ifak)*Math.abs(difLen)+Math.abs(ifak));
        }else{
            final int imod = i*10;
            
            return imod*ifak+ifak+difLen;            
        }
         
        
    }
    
    
}
